<template> 
  <el-card class="form-container" shadow="never">
    <el-form :model="homeAdvertise"
             :rules="rules"
             ref="homeAdvertiseFrom"
             label-width="100px"
             size="small">
      <el-form-item label="广告名称：" prop="name">
        <el-input v-model="homeAdvertise.name" class="input-width"></el-input>
      </el-form-item>
      <!-- <el-form-item label="广告位置：">
        <el-select v-model="homeAdvertise.type">
          <el-option
            v-for="type in typeOptions"
            :key="type.value"
            :label="type.label"
            :value="type.value">
          </el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="开始时间：" prop="startTime">
        <el-date-picker
          type="datetime"
          placeholder="选择日期"
          v-model="homeAdvertise.startTime"></el-date-picker>
      </el-form-item>
      <el-form-item label="到期时间：" prop="endTime">
        <el-date-picker
          type="datetime"
          placeholder="选择日期"
          v-model="homeAdvertise.endTime"></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="上线/下线：">
        <el-radio-group v-model="homeAdvertise.status">
          <el-radio :label="0">下线</el-radio>
          <el-radio :label="1">上线</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item label="广告图片：" required="">
        <single-upload v-model="homeAdvertise.pic" tip="请上传 750*370px 的图片"></single-upload>
      </el-form-item>
     
      <el-form-item label="选择仓库" required prop="depotId">
        <el-select v-model="homeAdvertise.depotId">
          <el-option
            v-for="dept in depotList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型：" prop="type">
        <el-radio v-model="homeAdvertise.type" label="1" size="medium">产品详情</el-radio>
        <el-tooltip class="item" effect="dark" content="需要在本仓库下的推荐版块中维护内容后，再进行关联" placement="top">
          <el-radio v-model="homeAdvertise.type" label="2" size="medium">推荐版块</el-radio>
        </el-tooltip>
        <el-radio v-model="homeAdvertise.type" label="3" size="medium">产品列表</el-radio>
        <el-radio v-model="homeAdvertise.type" label="4" size="medium">自定义页面</el-radio>
      </el-form-item>

      <el-form-item label="关联商品" required v-if="homeAdvertise.type == 1 ">
        <el-table v-if="homeAdvertise.productSingle.length>0" ref="productRelationTable" :data="homeAdvertise.productSingle"
                style="width: 100%;" border>
          <el-table-column label="编号" width="100" align="center">
            <template slot-scope="scope">{{scope.row.id}}</template>
          </el-table-column>
          <el-table-column label="商品名称" width="200" align="center">
            <template slot-scope="scope">{{scope.row.name}}</template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center" >
            <template slot-scope="scope">
              <el-button size="mini"
                        type="text"
                        @click="handleDeleteProduct(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button size="mini" class="btn-add" v-if="homeAdvertise.productSingle.length == 0"  @click="handleSelectProduct()" style="margin-left: 20px">添加关联商品</el-button>
      </el-form-item>
      <el-form-item label="关联商品" required v-if="homeAdvertise.type == 3">
        <el-table ref="productRelationTable" :data="homeAdvertise.productList"
                style="width: 100%;" border v-if="homeAdvertise.productList.length>0">
          <el-table-column label="编号" width="80" align="center">
            <template slot-scope="scope">{{scope.row.id}}</template>
          </el-table-column>
          <el-table-column label="商品名称" width="200" align="center">
            <template slot-scope="scope">{{scope.row.name}}</template>
          </el-table-column>
          <el-table-column label="排序" width="150" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sort"></el-input></template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleDeleteProduct(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button size="mini" class="btn-add" @click="handleSelectProduct()" style="margin-left: 20px">添加关联商品</el-button>
      </el-form-item>
      <el-form-item label="推荐版块" required v-if="homeAdvertise.type == 2" prop="blocks">
        <el-table ref="productRelationTable" :data="homeAdvertise.blocks"
                style="width: 100%;" border v-if="homeAdvertise.blocks.length>0">
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="板块名称" width="276" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
         <el-table-column label="操作" width="80" align="center" >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleDeleteBlock(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
        </el-table>
        <el-button size="mini" class="btn-add" @click="handleSelectBlock()" style="margin-left: 20px">添加关联板块</el-button>
      </el-form-item>
      <el-form-item label="自定义：" prop="url" v-if="homeAdvertise.type == 4">
        <tinymce :width="560" :height="300" v-model="homeAdvertise.url"></tinymce>
      </el-form-item>
      
      <!-- <el-form-item label="广告链接：" prop="url">
        <el-input v-model="homeAdvertise.url" class="input-width"></el-input>
      </el-form-item> -->
       <el-form-item label="排序：">
        <el-input v-model="homeAdvertise.sort" class="input-width"></el-input>
      </el-form-item>
      <el-form-item label="广告备注：">
        <el-input
          class="input-width"
          type="textarea"
          :rows="5"
          placeholder="请输入内容"
          v-model="homeAdvertise.note">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('homeAdvertiseFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm('homeAdvertiseFrom')">重置</el-button>
      </el-form-item>
    </el-form>
        <!-- 选择商品的弹窗 -->
    <el-dialog title="选择商品" :visible.sync="selectDialogVisible" width="50%">
      <span>
          选择仓库：
         <el-select v-model="dialogData.listQuery.depotId">
          <el-option
            v-for="dept in depotList"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id">
          </el-option>
        </el-select>
      </span>
      <el-input v-model="dialogData.listQuery.keyword"
                style="width: 250px;margin-bottom: 20px"
                size="small"
                placeholder="商品名称搜索">
        <el-button slot="append" icon="el-icon-search" @click="handleSelectSearch()"></el-button>
      </el-input>
      <el-table :data="dialogData.list"
                @selection-change="handleDialogSelectionChange" border>
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="商品图片" align="center">
          <template slot-scope="scope">
            <img style="max-width: 260px;max-height:60px;" :src="scope.row.pic" />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column label="货号" width="160" align="center">
          <template slot-scope="scope">NO.{{scope.row.productSn}}</template>
        </el-table-column>
        <el-table-column label="价格" width="120" align="center">
          <template slot-scope="scope">{{moneyIcon}}{{scope.row.price}}</template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleDialogSizeChange"
          @current-change="handleDialogCurrentChange"
          layout="prev, pager, next"
          :current-page.sync="dialogData.listQuery.pageNum"
          :page-size="dialogData.listQuery.pageSize"
          :page-sizes="[5,10,15]"
          :total="dialogData.total">
        </el-pagination>
      </div>
      <div style="clear: both;"></div>
      <div slot="footer">
        <el-button  size="small" @click="selectDialogVisible = false">取 消</el-button>
        <el-button  size="small" type="primary" @click="handleSelectDialogConfirm()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 选择板块的弹窗 -->
     <el-dialog title="选择板块" :visible.sync="selectBlockDialog" width="50%">
      <el-table :data="recommendBlocks"
                @selection-change="handleBlockDialogSelectionChange" border>
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="板块名称" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column label="背景图片" width="360" align="center">
          <template slot-scope="scope">
            <img style="height: 80px" :src="scope.row.pic">
          </template>
        </el-table-column>
      </el-table>
      <div style="clear: both;"></div>
      <div slot="footer">
        <el-button  size="small" @click="selectBlockDialog = false;">取 消</el-button>
        <el-button  size="small" type="primary" @click="handleSelectBlockConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
  import SingleUpload from '@/components/Upload/singleUpload'
  import {createHomeAdvertise, getHomeAdvertise, updateHomeAdvertise,fetchRelatedProductList, updateRelatedProduct,delRelatedProductList} from '@/api/homeAdvertise'
  import {fetchList as fetchDeptList} from '@/api/depository'
  import {fetchList as fetchProductList} from '@/api/product';
  import {fetchList as fetchBlockList} from '@/api/block';
  import {getProduct as getProductDetial} from '@/api/product';
  import Tinymce from '@/components/Tinymce'
  import MultiUpload from '@/components/Upload/multiUpload'
  const defaultTypeOptions = [
    {
      label: 'PC首页轮播',
      value: 0
    },
    {
      label: 'APP首页轮播',
      value: 1
    }
  ];
  const defaultHomeAdvertise = {
    name: null,
    type: '1',
    pic: null,
    startTime: null,
    endTime: null,
    status: 1,
    url: null,
    note: null,
    sort: 0,
    depotId:null,
    // productId:null,
    // subjectId:null,
    productList:[],
    productSingle:[],
    blocks:[],
  };
  export default {
    name: 'HomeAdvertiseDetail',
    components:{SingleUpload, MultiUpload, Tinymce},
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        moneyIcon:process.env.MONEY_ICON,
        recommendBlocks:[],//推荐版块
        selectDialogVisible:false,//选择商品的弹窗
        selectBlockDialog:false,//选择专题的弹窗
        homeAdvertise: Object.assign({}, defaultHomeAdvertise),
        rules: {
          name: [
            {required: true, message: '请输入广告名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
          url: [
            {required: true, message: '请输入具体内容', trigger: 'blur'}
          ],
          startTime: [
            {required: true, message: '请选择开始时间', trigger: 'blur'}
          ],
          endTime: [
            {required: true, message: '请选择到期时间', trigger: 'blur'}
          ],
          pic: [
            {required: true, message: '请选择广告图片', trigger: 'blur'}
          ],
          depotId:[
            {required:true, message:'请选择仓库',trigger:"blur"}
          ]
        },
        dialogData:{
          list: null,
          total: null,
          multipleSelection:[],
          listQuery:{
            keyword: null,
            pageNum: 1,
            pageSize: 5,
            publishStatus:1,
            verifyStatus:1,
          },
          depotId:null
        },
        typeOptions: Object.assign({}, defaultTypeOptions),
        depotList:[],//仓库列表
        //depotId:null,//仓库id
      }
    },
    created(){
      this.getDepotList();
      if (this.isEdit) {
        getHomeAdvertise(this.$route.query.id).then(response => {
          this.homeAdvertise = Object.assign(this.homeAdvertise,response.data);//response.data;
          this.homeAdvertise.type = this.homeAdvertise.type+'';
          // if(this.homeAdvertise.type == 1 && this.homeAdvertise.url){
            
          //   let pid = this.homeAdvertise.url;
          //   getProductDetial(pid).then(res=>{
          //     let data = res.data;
          //     if(data ){
          //       this.homeAdvertise.productSingle[0] = data;
          //       console.log( this.homeAdvertise)
          //       this.$forceUpdate();
          //     }
          //   })
          // }
          if(this.homeAdvertise.type == 1 || this.homeAdvertise.type == 3){
            this.getRelatedProducts();
          }
          if(this.homeAdvertise.type ==2){
            this.getBlockList('true');
          }
        });
      }else{
        this.homeAdvertise = Object.assign({},defaultHomeAdvertise);
      }
    },
    methods: {
      getBlockList(callback){
        let self = this;
        let listQuery ={
          pageNum: 1,
          pageSize: 50,
        }
        fetchBlockList(self.$route.query.depotId,listQuery).then(response => {
          self.recommendBlocks = response.data.list;
          if(callback && self.homeAdvertise.type == 2){//推荐版块，编辑状态时要把之前的数据显示出来
            let relatedSubjectId = self.homeAdvertise.subjectId;
            self.recommendBlocks.map(item=>{
              if(item.id == relatedSubjectId){
                // self.homeAdvertise.blocks.push(item);
                self.homeAdvertise.blocks[0] =  item;
              }
            })
          }
        })
      },
      // getRelatedProducts(){
      //   let pid = this.homeAdvertise.url;
      //   fetchRelatedProductList(pid).then(res=>{
      //     let data = res.data;
      //     if(data ){
      //       if(this.homeAdvertise.type == 1){
      //         this.homeAdvertise.productSingle = res.data && res.data.length>0?res.data:[];
      //         this.selectBlockDialog = false;
      //         this.homeAdvertise.block=[];
      //       }
      //       if(this.homeAdvertise.type == 3){
      //         this.homeAdvertise.productList = res.data && res.data.length>0?res.data:[];
      //         this.selectDialogVisible= false;
      //         this.dialogData.multipleSelection=[];
      //       }
      //       this.$forceUpdate();
      //     }else{
      //       if(this.homeAdvertise.type == 1){
      //         this.selectBlockDialog = false;
      //         this.homeAdvertise.block=[];
      //       }
      //       if(this.homeAdvertise.type == 3){
      //         this.selectDialogVisible= false;
      //         this.dialogData.multipleSelection=[];
      //       }
      //     }
      //   })
      // },
        handleSelectProduct(){
        this.selectDialogVisible=true;
        this.getDialogList();
      },
      handleSelectBlock(){
        this.selectBlockDialog=true;
        this.getBlockList();
      },
      handleDeleteBlock(){
        this.homeAdvertise.blocks = [];
        this.$forceUpdate();
      },
      getDialogList(){
        fetchProductList(this.dialogData.listQuery).then(response=>{
          this.dialogData.list=response.data.list;
          this.dialogData.total=response.data.total;
        })
      },
      handleSelectSearch(){
        this.getDialogList();
      },
      handleDialogSizeChange(val) {
        this.dialogData.listQuery.pageNum = 1;
        this.dialogData.listQuery.pageSize = val;
        this.getDialogList();
      },
      handleDialogCurrentChange(val) {
        this.dialogData.listQuery.pageNum = val;
        this.getDialogList();
      },
      handleDialogSelectionChange(val){
        if(this.homeAdvertise.type==1){//1，商品详情，只能选择1个商品
          if(val.length>1){
            this.$message({
              message: '只能选择1个商品',
              type: 'warning',
              duration: 1000
            });
            return
          }
        }
        this.dialogData.multipleSelection = val;
        this.$forceUpdate();
      },
      handleBlockDialogSelectionChange(val){
        if(val.length <1)return;
        let isCountinued = true;
        if(this.homeAdvertise.type==2){//1，商品详情，只能选择1个商品
          if(val.length>1){
            this.$message({
              message: '只能选择1个板块',
              type: 'warning',
              duration: 1000
            });
            isCountinued = false;
            return
          }
        }
        if(isCountinued){
          this.homeAdvertise.blocks = val;
          this.homeAdvertise.subjectId = val[0].id;
        }
      },
      
      handleSelectDialogConfirm(){
        if (this.dialogData.multipleSelection < 1) {
          this.$message({
            message: '请选择一条记录',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        if(this.homeAdvertise.type ==1){
          this.homeAdvertise.productSingle = this.homeAdvertise.productSingle.concat(this.dialogData.multipleSelection);
          this.homeAdvertise.productId = this.homeAdvertise.productSingle[0].id || null;
        }
        if(this.homeAdvertise.type ==3){
          this.homeAdvertise.productList = this.homeAdvertise.productList.concat(this.dialogData.multipleSelection);
        }
        this.$forceUpdate();
        this.selectDialogVisible = false;//关闭弹窗
      },
      handleSelectBlockConfirm(){
        if (this.homeAdvertise.blocks.length < 1) {
          this.$message({
            message: '请选择一条记录',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        this.selectBlockDialog = false;//关闭弹窗
      },
      updateRelatedProduct(resourcesId){
        let paramsObj={};
        let self = this;
        paramsObj.advertiseId = this.isEdit?this.$route.query.id:resourcesId;
        paramsObj.advertiseRelations = this.homeAdvertise.type == 3?this.homeAdvertise.productList:this.homeAdvertise.productSingle
        
        if(paramsObj && paramsObj.advertiseRelations.length>0){
          paramsObj.advertiseRelations.map(item=>{
            item.productId = item.id;//item.product?item.product.id : item.id;
            item.sort = item.sort;
            item.advertiseId = paramsObj.advertiseId;
            delete item.product
          })
          console.log('关联商品传参');
          console.log(paramsObj);
          updateRelatedProduct(paramsObj).then(response=>{
            // if(response.code ==200 ){
            //   self.getRelatedProducts(paramsObj.resourcesId);
            // }
          });
        }else{
          return;
        }
      },
      getRelatedProducts(resourcesId){
        let rid = this.$route.query.id?this.$route.query.id:resourcesId;
        fetchRelatedProductList(rid).then(res=>{
          let data = res.data;
          if(data && data.length>0){
            data.map(item=>{
              // item.name = item.product.name;
              item.aid = item.id;
              item.id = JSON.parse(JSON.stringify(item.pid));
              
            })
            if(this.homeAdvertise.type == 1){
              this.homeAdvertise.productSingle = res.data && res.data.length>0?res.data:[];
              this.selectBlockDialog = false;
              this.homeAdvertise.block=[];
            }
            if(this.homeAdvertise.type == 3){
              this.homeAdvertise.productList = res.data && res.data.length>0?res.data:[];
              this.selectDialogVisible= false;
              this.dialogData.multipleSelection=[];
            }
            this.$forceUpdate();
          }else{
            if(this.homeAdvertise.type == 1){
              this.selectBlockDialog = false;
              this.homeAdvertise.block=[];
            }
            if(this.homeAdvertise.type == 3){
              this.selectDialogVisible= false;
              this.dialogData.multipleSelection=[];
            }
          }
        })
      },
      handleDeleteProduct(index,row){
        if(!this.isEdit || this.homeAdvertise.type ==1){//新增状态，可以删除数据,,,,后端人员接口质量太差，所以单个商品的时候，前端自己来处理
          if(this.homeAdvertise.type==3){
            let delIdx = this.homeAdvertise.productList.indexOf(row);
            this.homeAdvertise.productList.splice(delIdx,1);
          }
          if(this.homeAdvertise.type ==1){
            this.homeAdvertise.productSingle = [];
          }
          this.$forceUpdate();
          return;
        }
        // let curId = row.aid;
        let deleteIds= [row.aid];
        if(!deleteIds[0]){
          let delIdx = this.homeAdvertise.productList.indexOf(row);
          this.homeAdvertise.productList.splice(delIdx,1);
          return;
        }
        this.$confirm('是否删除商品', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delRelatedProductList(deleteIds).then(res=>{
            if(res.code ==200){
              this.$message({
                message: '删除成功',
                type: 'success',
                duration:1000
              });
              this.getRelatedProducts();
            }
          })
        })
      },
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              if(this.homeAdvertise.type ==1){
                this.homeAdvertise.url = this.homeAdvertise.productSingle[0].id
              }
              console.log(this.homeAdvertise);
              if (this.isEdit) {
                updateHomeAdvertise(this.$route.query.id, this.homeAdvertise).then(response => {
                  if(response.code == 200 ){
                    if(this.homeAdvertise.type ==1 || this.homeAdvertise.type ==3){
                      this.updateRelatedProduct();
                    }
                    this.$refs[formName].resetFields();
                    this.$message({
                      message: '修改成功',
                      type: 'success',
                      duration:1000
                    });
                    this.$router.back();
                  }
                });
              } else {
                createHomeAdvertise(this.homeAdvertise).then(response => {
                  if(response.code ==200){
                    if(this.homeAdvertise.type ==1 || this.homeAdvertise.type ==3){
                      this.updateRelatedProduct(response.data);
                    }
                    this.$refs[formName].resetFields();
                    this.homeAdvertise = Object.assign({},defaultHomeAdvertise);
                    this.$message({
                      message: '提交成功',
                      type: 'success',
                      duration:1000
                    });
                    this.$router.back();
                  }
                  
                });
              }
            });

          } else {
            this.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.homeAdvertise = Object.assign({},defaultHomeAdvertise);
      },
      getDepotList(){
        let self = this;
        this.listLoading = true;
        fetchDeptList().then(({code,data})=>{
          if(code ==200 && data){
            this.depotList = data;
          }
        })
      }
    }
  }
</script>
<style scoped>
  .input-width {
    width: 70%;
  }
  .el-card__body{
    padding: 0;
  }
</style>


